//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	SiteQueryViewFields.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System.Collections.Generic;

namespace Smart.Common.Entities
{
	/// <summary>
	/// Site query view fields
	/// </summary>
	public class SiteQueryViewFields
	{
		public class ViewFieldInfo
		{
			public string Tag;
			public string Name;
			public string Type;
			public bool Nullable;

			public string Format(MetaFields meta)
			{
				string res;

				if (Tag.EqIC("FieldRef"))
				{
					var mf = meta.Field(Name);

					if (mf != null)
					{
						Name = mf.Name;
						Type = mf.Type.ToString();
						Nullable = Name.Out(SN.IDField); // SN.TitleField could be NULL
					}
					else
					{
						Type = "Text";
						Nullable = true;
					}

					res =
						string.Format("<{0} Name=\"{1}\" Type=\"{2}\" Nullable=\"{3}\" />", Tag, Name, Type, Nullable);
				}
				else
				{
					res =
						string.Format("<{0} Name=\"{1}\" />", Tag, Name);
				}

				return res;
			}
		}

		/// <summary>
		/// Fields list
		/// </summary>
		public List<ViewFieldInfo> Fields { get; set; }

		/// <summary>
		/// Site data query
		/// </summary>
		public SiteQuery SiteQuery { get; set; }

		/// <summary>
		/// Site query view fields
		/// </summary>
		public SiteQueryViewFields(SiteQuery siteQuery)
		{
			SiteQuery = siteQuery;

			Fields = new List<ViewFieldInfo>();
		}

		/// <summary>
		/// Format site query ViewFields
		/// </summary>
		/// <returns></returns>
		public virtual string Format()
		{
			if (Fields.Count <= 0)
				return null;

			var meta = SiteQuery.Meta;

			return
				Fields.CastToString(string.Empty, info => info.Format(meta));
		}
	}
}